//
//  OrderDetailsViewController.m
//  dangdang
//
//  Created by air on 16/2/7.
//  Copyright © 2016年 luweijie. All rights reserved.
//

#import "OrderDetailsViewController.h"
#import "OrderDetailsFirstTableViewCell.h"
#import "OrderDetailsSecondTableViewCell.h"
#import "OrderDetailsThirdTableViewCell.h"
#import "OrderDetailsForthTableViewCell.h"
#import "CheckMapViewController.h"
#import "OrderDetailsObject.h"
#import "AcountBalanceViewController.h"
#import "MyBillViewController.h"
#import "InProgressViewController.h"
#import "EvaluateViewController.h"
#import "CompleteViewController.h"
#import "RefundViewController.h"
#import "CancelViewController.h"

@interface OrderDetailsViewController ()

@property (nonatomic, strong) NSDictionary * ordersDic;
@property (nonatomic, strong) OrderDetailsObject * detailsObject;

@end

@implementation OrderDetailsViewController

- (instancetype)init {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"OrderDetailsViewController" bundle:nil];
    self = [sb instantiateViewControllerWithIdentifier:@"OrderDetailsViewController"];
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self updateUI];
    
    [self connection];
    
//    [self buttonLayout];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (userObject.array.count == 2 && [userObject.pay_status isEqualToString:@"0"] && [userObject.orderPay isEqualToString:@"bill"]) {
        _payLabel.text = [NSString stringWithFormat:@"￥%@", userObject.fee];
    }else{
        _bottonView.hidden = YES;
    }
    if ([_judge isEqualToString:@"sucess"]) {
        [self addBottomView];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    userObject.orderStatus = @"";
    _judge = @"";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addBottomView{
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(self.view.center.x - 60, self.view.bounds.size.height - 120, 120, 40)];
    __block int timeout = 2; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [label removeFromSuperview];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                label.backgroundColor = [UIColor blackColor];
                label.text = @"成功支付";
                label.textAlignment = NSTextAlignmentCenter;
                label.textColor = [UIColor whiteColor];
                label.font = [UIFont boldSystemFontOfSize:16.0f];
                label.layer.cornerRadius = 10;
                label.layer.masksToBounds = YES;
                [self.view addSubview:label];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

- (void)connection{
    NSString * token = userObject.accessToken;
    NSString * userIDString = userObject.userID;
    NSString * orderIDString = userObject.ordID;
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:token forKey:@"token"];
    [params setObject:userIDString forKey:@"uid"];
    [params setObject:orderIDString forKey:@"order_id"];
    
    [self postRequestWithMethodName:@"order/get_order" andParams:params andSender:nil];
}

- (void)buttonLayout{
    UIButton * bottomButton = [[UIButton alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 50, self.view.frame.size.width, 50)];
    bottomButton.backgroundColor = [UIColor orangeColor];
    [bottomButton setTitle:@"马上抢单" forState:UIControlStateNormal];
    bottomButton.titleLabel.font = [UIFont systemFontOfSize:20.0];
    [bottomButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [bottomButton addTarget:self action:@selector(confirmBill) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bottomButton];
}

- (void)confirmBill{
    NSString * token = userObject.accessToken;
    NSString * userIDString = userObject.userID;
    NSString * orderIDString = userObject.ordID;
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:token forKey:@"token"];
    [params setObject:userIDString forKey:@"uid"];
    [params setObject:orderIDString forKey:@"order_id"];
    
    [self postRequestWithMethodName:@"order/competition_order" andParams:params andSender:nil];
}

- (void)updateUI{
    _orderDetailsTableView.rowHeight = UITableViewAutomaticDimension;
    _orderDetailsTableView.estimatedRowHeight = 44.0;
    
    _rejectButton.layer.cornerRadius = 8;
    _agreeButton.layer.cornerRadius = 8;
    
    if (self.view.frame.size.width == 320) {
        _payLabel.font = [UIFont systemFontOfSize:17.0];
        _rejectButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
        _agreeButton.titleLabel.font = [UIFont systemFontOfSize:15.0];
        _rejectButtonWidth.constant -= 20;
        _agreeButtonWidth.constant -= 10;
    }else if (self.view.frame.size.width == 414){
        _payLabel.font = [UIFont systemFontOfSize:19.0];
        _rejectButton.titleLabel.font = [UIFont systemFontOfSize:20.0];
        _agreeButton.titleLabel.font = [UIFont systemFontOfSize:20.0];
        _rejectButtonWidth.constant += 10;
        _agreeButtonWidth.constant += 30;
    }
    
    if ([userObject.orderStatus isEqualToString:@"grab"]) {
        _tableViewHeight.constant -= 50;
        [self buttonLayout];
    }
    _orderDetailsTableView.hidden = YES;
}

- (IBAction)bottomButton:(UIButton *)sender {
    if (sender.tag == 0) {
        NSString * token = userObject.accessToken;
        NSString * userIDString = userObject.userID;
        NSString * orderIDString = userObject.ordID;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:userIDString forKey:@"uid"];
        [params setObject:orderIDString forKey:@"order_id"];
        
        [self postRequestWithMethodName:@"order/refuse_order" andParams:params andSender:nil];
    }else{
        NSString * token = userObject.accessToken;
        NSString * userIDString = userObject.userID;
        NSString * orderIDString = userObject.ordID;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:userIDString forKey:@"uid"];
        [params setObject:orderIDString forKey:@"order_id"];
        
        [self postRequestWithMethodName:@"order/accpet_order" andParams:params andSender:nil];
    }
}

#pragma mark UITableViewDataSource && Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    if (indexPath.section == 0) {
        OrderDetailsFirstTableViewCell * firstCell = [tableView dequeueReusableCellWithIdentifier:@"orderDetailsFirstTableViewCell"];
        
        firstCell.reachTimeLabel.text = _detailsObject.reach_time;
        firstCell.exp_feeLabel.text = [NSString stringWithFormat:@"￥%@元", _detailsObject.exp_fee];
        firstCell.itemPriceLabel.text = [NSString stringWithFormat:@"￥%@元", _detailsObject.item_price];
        
        cell = firstCell;
    }
    if (indexPath.section == 1){
        OrderDetailsSecondTableViewCell * secondCell = [tableView dequeueReusableCellWithIdentifier:@"orderDetailsSecondTableViewCell"];
        
        secondCell.remarkLabel.text = [NSString stringWithFormat:@"￥%@", _detailsObject.remark];
        
        cell = secondCell;
    }
    if (indexPath.section == 2){
        OrderDetailsThirdTableViewCell * thirdCell = [tableView dequeueReusableCellWithIdentifier:@"orderDetailsThirdTableViewCell"];
        [thirdCell.checkMapButton addTarget:self action:@selector(checkMap:) forControlEvents:UIControlEventTouchUpInside];
        
        if ([_detailsObject.item_buy_location_name isEqualToString:@"<null>"]) {
            thirdCell.buyLocationLabel.text = @"不限";
        }else{
            thirdCell.buyLocationLabel.text = _detailsObject.item_buy_location_name;
        }
        
        thirdCell.locationLabel.text = _detailsObject.location_name;
        
        cell = thirdCell;
    }
    if (indexPath.section == 3){
        OrderDetailsForthTableViewCell * forthCell = [tableView dequeueReusableCellWithIdentifier:@"orderDetailsForthTableViewCell"];
        
        forthCell.itemNameLabel.text = _detailsObject.item_name;
        forthCell.itemPriceLabel.text = [NSString stringWithFormat:@"￥%@元", _detailsObject.item_price];
        forthCell.itemWeightLabel.text = [NSString stringWithFormat:@"%@kg", _detailsObject.item_weight];
        
        cell = forthCell;
    }
    
    cell.layer.borderWidth = 1;
    cell.layer.borderColor = [[[UIColor lightGrayColor] colorWithAlphaComponent:0.5] CGColor];
    cell.layer.cornerRadius = 8;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1f;
}

- (void)checkMap:(UIButton *)button{
    CheckMapViewController * mapboardVC = [[CheckMapViewController alloc] init];
    mapboardVC.lng = _detailsObject.location_lng;
    mapboardVC.lat = _detailsObject.location_lat;
    
    [self.navigationController pushViewController:mapboardVC animated:YES];
}

//网络连接返回数据
- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender{
    
    NSString * urlString = [NSString stringWithFormat:@"%@", task.currentRequest.URL];
    
    if ([result isKindOfClass:[NSDictionary class]]) {
        NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
        if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"order/get_order"]]) {
            if ([code isEqualToString:@"0"]){
                _ordersDic = [result objectForKey:@"retmsg"];
                _detailsObject = [[OrderDetailsObject alloc] init];
                _detailsObject.reach_time = [NSString stringWithFormat:@"%@", [_ordersDic objectForKey:@"reach_time"]];
                _detailsObject.exp_fee = [NSString stringWithFormat:@"%@", [_ordersDic objectForKey:@"exp_fee"]];
                _detailsObject.item_price = [NSString stringWithFormat:@"%@", [_ordersDic objectForKey:@"item_price"]];
                _detailsObject.remark = [NSString stringWithFormat:@"%@", [_ordersDic objectForKey:@"remark"]];
                _detailsObject.location_name = [NSString stringWithFormat:@"%@", [_ordersDic objectForKey:@"location_name"]];
                _detailsObject.location_lng = [NSString stringWithFormat:@"%@", [_ordersDic objectForKey:@"location_lng"]];
                _detailsObject.location_lat = [NSString stringWithFormat:@"%@", [_ordersDic objectForKey:@"location_lat"]];
                _detailsObject.item_name = [NSString stringWithFormat:@"%@", [_ordersDic objectForKey:@"item_name"]];
                _detailsObject.item_weight = [NSString stringWithFormat:@"%@", [_ordersDic objectForKey:@"item_weight"]];
                _detailsObject.item_buy_location_name = [NSString stringWithFormat:@"%@", [_ordersDic objectForKey:@"item_buy_location_name"]];
                
                [_orderDetailsTableView reloadData];
                _orderDetailsTableView.hidden = NO;
            }
        }else if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"order/competition_order"]]){
            if ([code isEqualToString:@"0"]) {
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:@"抢单成功" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    MyBillViewController *pageController = [[MyBillViewController alloc] init];
                    NSArray *viewControllerClasses = @[[InProgressViewController class], [EvaluateViewController class], [CompleteViewController class], [RefundViewController class], [CancelViewController class]];
                    NSArray *titles = @[@"进行中", @"待评价", @"已完成", @"已退款", @"已取消"];
                    pageController.viewControllerClasses = viewControllerClasses;
                    pageController.titles = titles;
                    pageController.menuItemWidth = self.view.frame.size.width / 5;
                    pageController.menuViewStyle = WMMenuViewStyleLine;
                    pageController.titleSizeSelected = 15.0;
                    pageController.titleName = @"我的订单";
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:pageController];
                        [self presentViewController:navi animated:YES completion:nil];
                    });
                }];
                [alertVC addAction:action];
                [self presentViewController:alertVC animated:YES completion:nil];
            }else{
                [self alertViewShowWithAlertString:[NSString stringWithFormat:@"%@", [result objectForKey:@"errmsg"]]];
            }
        }else if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"order/refuse_order"]]){
            [self.navigationController popViewControllerAnimated:YES];
        }else if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"order/accpet_order"]]){
            AcountBalanceViewController * acountboardVC = [[UIStoryboard storyboardWithName:@"AcountBalanceViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"AcountBalanceViewController"];
            
            acountboardVC.bill = @"order";
            
            acountboardVC.orderViewController = self;
            
            [self.navigationController pushViewController:acountboardVC animated:YES];
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
